package 算法.leetcode.str;

import org.junit.Test;

/**
 * @author lchenglong
 * @date 2020/12/7
 */
public class MyAtoi {

    @Test
    public void test(){
        System.out.println(myAtoi("+"));
    }

    public int myAtoi(String s) {
        if (s == null||(s = s.trim()).length()==0) {
            return 0;
        }
        int flag = s.charAt(0) == '-'?-1:1;
        StringBuilder sb = new StringBuilder();
        for (int i=0,size = s.length();i<size;i++) {
            char cur = s.charAt(i);
            if (i == 0) {
                if (cur == '-'|| cur == '+') {
                    continue;
                }
            }
            if (cur < 48 || cur > 57) {
                if (sb.length() == 0) {
                    return 0;
                } else {
                    break;
                }
            } else {
                sb.append(cur);
            }
        }
        while (sb.length()>0 &&sb.charAt(0) == '0') {
            sb.deleteCharAt(0);
        }
        if (sb.length()>10) {
            sb = new StringBuilder("10000000000");
        }
        long res = sb.length() ==0?0:Long.parseLong(sb.toString());
        if (flag ==1 && res > (Math.pow(2,31)  -1)) {
            return (int) (Math.pow(2,31)  -1);
        }
        if (flag == -1 && res > Math.pow(2,31)) {
            return (int) (-Math.pow(2,31));
        }
        return (int) (res * flag);
    }
}
